package com.refusea.train.domain.helper

import com.refusea.train.config.mvc.WebSession
import com.refusea.train.domain.cache.TokenCache
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.domain.req.UserUpdateReq
import com.refusea.train.mapper.UserMapper
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component

/**
 * @author Zhang Yan 2024/3/27
 **/
@Component
class UserUpdateHelper(
    private val userMapper: UserMapper,
    private val passwordEncoder: PasswordEncoder,
    private val tokenCache: TokenCache,
) {

    fun update(req: UserUpdateReq) {

        val user = WebSession.user()

        if (req.type == 1) {
            if (req.name == null) {
                throw BizEx.of("姓名不能为空")
            }
            if (req.name != user.name) {
                userMapper.updateName(user.id, req.name)
            }
        } else if (req.type == 2) {
            if (req.password.isNullOrEmpty() || req.newPassword.isNullOrEmpty()) {
                throw BizEx.of("密码不能为空")
            }
            if (!passwordEncoder.matches(req.password, user.password)) {
                throw BizEx.of("原密码错误")
            }
            if (req.password != req.newPassword) {
                userMapper.updatePassword(user.id, passwordEncoder.encode(req.newPassword))
            }
        } else {
            throw BizEx.of("参数错误：type=${req.type}")
        }

        // 更新缓存
        val u = userMapper.select(user.id)!!
        val token = WebSession.token()
        tokenCache.put(token, u)
        WebSession.hold(token, u)
    }
}
